<!--
 * @Description: 地址展示页面
 * @Author: Gaq
 * @Date: 2022-11-05 17:26:43
 * @LastEditTime: 2022-11-12 11:08:37
 * @LastEditors: Gaq
-->
<script setup>
import request from "@/utils/request";
import { ElMessage } from "element-plus";
import { useStore } from "vuex";

const { state, dispatch } = useStore();

let addressData = computed(() => state.addressData);

const deleteData = (value) => {
  dispatch("deleteAddressObj", value);
};
const toDefault = (row, index) => {
  row.isDefault = 1;
  request.put("/address/updateOne", row);
  addressData.value.splice(index, 1);
  addressData.value.unshift(row);
  addressData.value.map((item) => {
    if (item.isDefault == 1 && item.addressId !== row.addressId) {
      item.isDefault = 0;
      request.put("/address/updateOne", item).then((res) => {
        if (res.code == 0) {
          ElMessage.success("设置成功");
        }
      });
    }
  });
};
</script>

<template>
  <div class="addAddress" style="width: 600px; margin: 30px 0px 40px 30px">
    <AddressForm></AddressForm>
  </div>
  <div class="addressTable" style="width: 950px; margin-left: 30px">
    <span
      ><el-alert
        :title="`已保存了${addressData.length}条地址`"
        type="success"
        :closable="false"
    /></span>
    <el-card class="box-card">
      <el-table :data="addressData" style="width: 100%">
        <el-table-column prop="name" label="收货人" width="100" />
        <el-table-column prop="region" label="所在地区" width="220" />
        <el-table-column prop="detail" label="详细地址" width="220" />
        <el-table-column prop="phoneNumber" label="手机号码" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-popconfirm
              title="确定删除吗？"
              @confirm="deleteData(scope.row)"
            >
              <template #reference>
                <el-button size="small" type="danger" plain>删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
        <el-table-column>
          <template #default="scope">
            <div v-show="scope.row.isDefault">
              <el-button size="small" type="primary" plain>默认地址</el-button>
            </div>
            <div v-show="!scope.row.isDefault">
              <el-button
                size="small"
                type="info"
                @click="toDefault(scope.row, scope.$index)"
                plain
                >设为默认</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<style scoped>
</style>